package datasource

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"github.com/irisProject/core/config"
	"log"
	"sync"
)

var (
	masterInstance  *xorm.Engine
	dbLock  sync.Mutex
)

// 得到唯一的主库实例
func InstanceMysql()  *xorm.Engine {
	if masterInstance != nil {
		return masterInstance
	}
	dbLock.Lock()
	defer dbLock.Unlock()
	if masterInstance != nil {
		return masterInstance
	}
	return NewDbMaster()
}

func NewDbMaster() *xorm.Engine {
	dbDriver := config.Conf.Section("database").Key("driver").String()
	dbHost := config.Conf.Section(dbDriver).Key("host").String()
	dbPort, _ := config.Conf.Section(dbDriver).Key("port").Int()
	userName := config.Conf.Section(dbDriver).Key("username").String()
	password := config.Conf.Section(dbDriver).Key("password").String()
	databaseName := config.Conf.Section(dbDriver).Key("dbname").String()
	sourceName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",
		userName,
		password,
		dbHost,
		dbPort,
		databaseName)

	instance, err := xorm.NewEngine(dbDriver, sourceName)
	if err != nil {
		log.Fatal("XORM 数据库连接出错:", err)
		return nil
	}
	instance.ShowSQL(true)
	masterInstance = instance
	return masterInstance
}
